package com.orhon.smartcampus.modules.baseinfo.fetcher;


import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.baseinfo.dao.SemesterDao;
import com.orhon.smartcampus.modules.baseinfo.entity.Semester;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLSemester;
import com.orhon.smartcampus.modules.baseinfo.mm.SemesterMapper;

import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.R;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SemesterFetcher implements DataFetcher {


	@Autowired
	SemesterDao semesterDao;

	@Autowired
	TokenService tokenService;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {
		String token = tokenService.getSystemToken();
		if(token==null) {
			return  R.NoLogin();
		}
		Long schoolId = JwtUtils.getSchoolId(token);

		int id = Integer.parseInt(env.getArgument("id").toString());

		String hql = "from Semester where deleted_at = null and id = "+id+" and school_id = " + schoolId;
		Semester item =  semesterDao.findId(hql, null);
		if(item!=null) {
			GQLSchool gqlSchool= null;
			if (env.getSelectionSet().contains("school")){
				Schools schools = item.getBaseSchoolsBySchoolId();
				gqlSchool = SchoolMapper.MAPPER.toSchool(schools);
			}

			GQLSemester semester = SemesterMapper.MAPPER.toSemester(item);
			semester.setSchool(gqlSchool);
			return semester;
		}
		return null;
	}


}
